package com.example.demo.service;

import com.example.demo.entity.Customer;
import com.example.demo.entity.Item;
import com.example.demo.entity.Order;
import com.example.demo.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.JoinType;
import javax.transaction.Transactional;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by pengwan on 2017/7/28.
 */
@Service
@Transactional // 保持session, 解决hibernate的懒加载异常问题
public class OrderService {
    @Autowired
    private OrderRepository orderRepository;
    public List<Order> fetchJoinTest(){
        Specification<Order> orderSpecification = (root, criteriaQuery, criteriaBuilder) -> {
            root.fetch(root.getModel().getSingularAttribute("customer", Customer.class),JoinType.INNER);
            root.fetch("items",JoinType.INNER); // here is one2many fetch
            return criteriaQuery.getRestriction();
        };
        List<Order> orderList = orderRepository.findAll(orderSpecification);
        // hibernate one2many fetch的时候会有重复记录(是否bug?)，因此借用set去重
        HashSet<Order> hashSet = new HashSet<>(orderList);
        orderList.clear();
        orderList.addAll(hashSet);
        return orderList;
    }

}
